package com.nuanshui.heatedloan.controller.display.pay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nuanshui.heatedloan.constant.PayType;
import com.nuanshui.framework.exception.BizException;
import com.nuanshui.framework.exception.GlobalErrorCode;
import com.nuanshui.framework.lang.SysStringUtils;
import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.heatedloan.controller.BaseController;
import com.nuanshui.heatedloan.fund.enums.PaymentBizType;
import com.nuanshui.heatedloan.fund.enums.PlatformEnum;
import com.nuanshui.heatedloan.fund.integration.form.PayForm;
import com.nuanshui.heatedloan.fund.integration.form.RequestPayForm;
import com.nuanshui.heatedloan.fund.integration.pay.execute.PayExecuteFacade;
import com.nuanshui.heatedloan.fund.model.PayResult;
import com.nuanshui.heatedloan.fund.model.PayResult.PayResultStatusType;
import com.nuanshui.heatedloan.userinfo.model.User;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付相关的接口
 * @param 
 * @author guohao
 * @date 2017年1月10日 下午5:56:01
 * @since $
 */
@RestController
@RequestMapping("/pay")
public class PayController  extends BaseController{

	private Logger logger = LoggerFactory.getLogger("pay_confirm");
	
	@Autowired
	private PayExecuteFacade payExecuteFacade;
	
	/**
	 * 获取要支付的支付号
	 * @param @return
	 * @author guohao
	 * @date 2017年1月10日 下午5:56:55
	 * @since $
	 */
	@RequestMapping(value = "/loadPayNum",method = RequestMethod.POST)
	public String loadPayNum(RequestPayForm requestPayForm,PaymentBizType fundType) {
		if(fundType == null) error("不支持的类型");
		requestPayForm.setPayBizType(fundType);
		requestPayForm.setUserId(getCurrentUser().getId());
		System.out.println(requestPayForm.getPayBizType());
		String orderNum = payExecuteFacade.loadPayNum(requestPayForm);
		return success(orderNum);
	}
	
	
	/**
	 * 第三方确认支付接口
	 * @param @return
	 * @author guohao
	 * @date 2017年1月11日 上午9:33:31
	 * @since $
	 */
	@RequestMapping(value = "/threePartyPayConfirm",method = RequestMethod.POST)
	public String threePartyPayConfirm(HttpServletRequest request) {
		StringBuilder json = new StringBuilder();
		String line = null;
		try {
			BufferedReader reader = request.getReader();
			while ((line = reader.readLine()) != null) {
				json.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		JSONObject jObject = JSON.parseObject(json.toString());
		if(jObject == null ) return "success";
		
		String sign = jObject.getString("sign");
		String timestamp = jObject.getString("timestamp");
		PayForm payForm = new PayForm();
		String opt = jObject.getString("transaction_type");// 获取是支付还是退款
		JSONObject optional = jObject.getJSONObject("optional");
		String orderNum = optional.getString("orderNum");// 订单号
		LogUtil.info(logger, "确认支付的订单号  "+orderNum);
		if(StringUtils.isEmpty(orderNum)) return "success"; //如果没有传入订单号直接返回
		if ("PAY".equals(opt)) {// 支付
			int price = jObject.getInteger("transaction_fee");// 支付的金钱
			String payType = jObject.getString("channel_type");// 获取支付方式
			payForm.setPayPrice(price);
			payForm.setPayType(payType);
			payForm.setSign(sign);
			payForm.setTimestamp(timestamp);
			payForm.setOrderNum(orderNum);
			PayResult payResult =  payExecuteFacade.executeConfirmPay(payForm);
			if(payResult.isSuccess()) {
				return "success";
			}else if(payResult.getStatus().equals(PayResultStatusType.AUTH_FAIL)) {
				//校验失败
				return "fail";
			}else {
				return "fail";
			}
		}		
		return "success";	
		
	}
	
	/**
	 * 预约支付回调确认接口
	 * @param @param payForm
	 * @param @return
	 * @author guohao
	 * @date 2017年1月11日 上午9:42:59
	 * @since $
	 */
	@RequestMapping(value = "/walletPayConfirm",method = RequestMethod.POST)
	public String walletPayConfirm(PayForm payForm){
		if(StringUtils.isEmpty(payForm.getOrderNum())) error("支付订单号有误");
		User user = getCurrentUser();
		if(user == null || SysStringUtils.isEmpty(user.getId())){
			throw new BizException(GlobalErrorCode.SIGN_ILLEGAL, "用户未登录");
		}
		payForm.setPayType(PlatformEnum.PLATFORM_YE.getName());
		payForm.setSafeToken(getSafeToken());
		payForm.setUserId(user.getId());
		payForm.setPhone(user.getPhone());
		Map<String, Object> map = new HashMap<String, Object>();
		PayResult payResult =  payExecuteFacade.executeConfirmPay(payForm);
		map.put("status",payResult.getStatus());	
		return success(map);		
	}	
}
